//
//  MRCustomNotificationsViewController.m
//  MoRan
//
//  Created by MoRan on 2024/1/20.
//  Copyright © 2024 MoRan. All rights reserved.
//

#import "MRCustomNotificationsViewController.h"

#import "MRCustomNotificationsCell.h"

#import "MRCustomNotificationsCutHeadView.h"
#import "MRCustomNotificationsAddToolBar.h"

#import "MRNewNotificationViewController.h"

#import <UserNotifications/UserNotifications.h>

@interface MRCustomNotificationsViewController () <UNUserNotificationCenterDelegate>

@property (nonatomic,copy) NSArray *notificationList;
@property (nonatomic,strong) MRCustomNotificationsCutHeadView *cutHeadView;
@property (nonatomic,assign) NSInteger index;
@property (nonatomic,strong) MRCustomNotificationsAddToolBar *toolBar; //提交按钮bar

@end

@implementation MRCustomNotificationsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib

    self.navigationBar.backgroundColor = [UIColor clearColor];
    [self setNavigationItemTitleViewWithTitle:@"自定义通知"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MRCustomNotificationsCell" bundle:nil] forCellReuseIdentifier:@"MRCustomNotificationsCell"];
    
    [self.cutHeadView setIndex:0];
    [self.view addSubview:self.cutHeadView];
    
    [self.view addSubview:self.toolBar];
    
    self.tableView.frame = CGRectMake(0,self.cutHeadView.frame.origin.y + self.cutHeadView.frame.size.height, kScreenWidth, kScreenHeight - (self.cutHeadView.frame.origin.y + self.cutHeadView.frame.size.height) - self.toolBar.frame.size.height);
    [self.view bringSubviewToFront:self.navigationBar];
    
    self.notificationList = [kDataManager getNotificationArrayWithIndex:_index];
    [self refreshData];
    
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 10.0) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                //点击允许
                NSLog(@"注册通知成功");
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    NSLog(@"========%@",settings);
                }];
            } else {
                //点击不允许
                NSLog(@"注册通知失败");
                // 3.GCD
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showSetAlertView];
                });
            }
        }];
        //注册推送（同iOS8）
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
}

- (void)showSetAlertView {

        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"需要你同意使用通知权限，才能为你进行本地通知推送" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //跳入当前App设置界面
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:setAction];
        
        UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
        [window.rootViewController presentViewController:alertVC animated:YES completion:nil];
    
}

#pragma mark - cellDataSource

- (NSArray *)cellDataSource {
    
    if (!self.dataSource) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
        
        __block NSMutableArray *subarr = nil;
        __block NSDictionary *dict = nil;

        if (self.notificationList.count > 0) {
            subarr = [NSMutableArray arrayWithCapacity:1];
            
            [self.notificationList enumerateObjectsUsingBlock:^(MRNotificationModel *msg, NSUInteger idx, BOOL * _Nonnull stop) {
                
                dict =  @{@"class":MRCustomNotificationsCell.class,
                          @"height":@([MRCustomNotificationsCell getCellFrame:[MRCustomNotificationsCellModel ittemModelWithIndex:_index msg:msg]]),
                          @"data":[MRCustomNotificationsCellModel ittemModelWithIndex:_index msg:msg],
                          @"delegate":@YES};
                [subarr addObject:dict];
            }];
            [arr addObject:subarr];
        }

        self.dataSource = arr;
    }
    return self.dataSource;
}


#pragma mark - goto

//新建通知
- (void)gotoNewNotificationViewController {
    MRNewNotificationViewController* vc = [MRNewNotificationViewController new];
    @weakify(self)
    vc.completion = ^(MRNewNotificationViewController *viewController,MRNotificationModel *msg) {
        @strongify(self);
        [kDataManager addNotificationDataWithModel:msg];
        [self registerNotification:msg];
        self.notificationList = [kDataManager getNotificationArrayWithIndex:self->_index];
        [self refreshData];
    };
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 懒加载

//底部工具条
- (MRCustomNotificationsCutHeadView *)cutHeadView {
    if (!_cutHeadView) {
        _cutHeadView = [MRCustomNotificationsCutHeadView instanceView];
        _cutHeadView.frame = CGRectMake(0,self.navigationBarHeight, kScreenWidth,70);
        @weakify(self)
        _cutHeadView.buttonAction = ^(MRCustomNotificationsCutHeadView *view, UIButton *sender) {
            @strongify(self);
            self->_index = sender.tag - 10;
            [view setIndex:self->_index];
            self.notificationList = [kDataManager getNotificationArrayWithIndex:self->_index];
            [self refreshData];
        };
    }
    return _cutHeadView;
}

//底部工具条
- (MRCustomNotificationsAddToolBar *)toolBar {
    if (!_toolBar) {
        _toolBar = [MRCustomNotificationsAddToolBar instanceView];
        _toolBar.frame = CGRectMake(0,kScreenHeight - 150, kScreenWidth,150);
        @weakify(self)
        _toolBar.buttonAction = ^(MRCustomNotificationsAddToolBar *toolBar, UIButton *sender) {
            @strongify(self);
            [self gotoNewNotificationViewController];
        };
    }
    return _toolBar;
}

-(void)registerNotification:(MRNotificationModel *)msg {
    // 1、创建通知内容，注：这里得用可变类型的UNMutableNotificationContent，否则内容的属性是只读的
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    // 标题
    content.title = kSafeString(msg.title);
    // 次标题
    content.subtitle = kSafeString(msg.subTitle);
    // 内容
    content.body = kSafeString(msg.content);
    
    // app显示通知数量的角标
    content.badge = [NSNumber numberWithInteger:0];
    
    // 通知的提示声音，这里用的默认的声音
    content.sound = [UNNotificationSound defaultSound];
    NSURL *imageUrl = [[NSBundle mainBundle] URLForResource:@"cell2@2x" withExtension:@"png"];
    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"imageIndetifier" URL:imageUrl options:nil error:nil];
    // 附件 可以是音频、图片、视频 这里是一张图片
//    content.attachments = @[attachment];  // TODO 填入附件
    // 标识符
    content.categoryIdentifier = @"categoryIndentifier";
    // 2、创建通知触发
    /* 触发器分三种： UNTimeIntervalNotificationTrigger : 在一定时间后触发，如果设置重复的话，timeInterval不能小于60 UNCalendarNotificationTrigger : 在某天某时触发，可重复 UNLocationNotificationTrigger : 进入或离开某个地理区域时触发 */

    NSString *specifiedTimeString = msg.time; // 指定的时间字符串
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *specifiedTime = [dateFormatter dateFromString:specifiedTimeString];

    NSTimeInterval timeInterval = [specifiedTime timeIntervalSinceNow];
    NSInteger seconds = (NSInteger)timeInterval;
    if (seconds < 0) {
        seconds = 10;
    }
    NSLog(@"指定时间距离当前时间：%ld秒", seconds);

    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:seconds repeats:NO];
    
    // 3、创建通知请求
    UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:msg.notificationId content:content trigger:trigger];
    // 4、将请求加入通知中心
    @weakify(self);
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
        @strongify(self);
        if (error == nil) {
            NSLog(@"已成功加推送%@",notificationRequest.identifier);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}


#pragma mark - iOS10 推送代理

//不实现，通知不会有提示
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    //应用在前台收到通知
    NSLog(@"========%@", notification);
    
    UNNotificationRequest *request = notification.request; // 原始请求
    NSDictionary * userInfo = notification.request.content.userInfo;//userInfo数据
    UNNotificationContent *content = request.content; // 原始内容
    NSString *title = content.title;  // 标题
    NSString *subtitle = content.subtitle;  // 副标题
    NSNumber *badge = content.badge;  // 角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 指定的声音
    //建议将根据Notification进行处理的逻辑统一封装，后期可在Extension中复用~
    //如果需要在应用在前台也展示通知
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 回调block，将设置传入
    
}

// 对通知进行响应
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
    
    [self handleResponse:response];
    
    UNNotificationRequest *request = response.notification.request; // 原始请求
    UNNotificationContent *content = request.content; // 原始内容
    NSString *title = content.title;  // 标题
    NSString *subtitle = content.subtitle;  // 副标题
    NSNumber *badge = content.badge;  // 角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;
    //在此，可判断response的种类和request的触发器是什么，可根据远程通知和本地通知分别处理，再根据action进行后续回调
    completionHandler();
}

- (void)handleResponse:(UNNotificationResponse *)response {
    
    NSString *actionIndentifier = response.actionIdentifier;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSLog(@"%@",@"处理通知");
    
}

@end
